/*
 * @Author: fishroom
 * @Date: 2023-01-05 14:01:53
 * @LastEditTime: 2023-01-09 15:10:24
 * @FilePath: \koa\app\socketHandler\sendHandler.ts
 */
import { Server as ServerIo } from "socket.io";
import ChitchatGroup from "./ChitchatGroup";
import ChitchatUser from "./ChitchatUser";
export default (
  io: ServerIo,
  userChitchat: Map<string, ChitchatUser>,
  groupChitchat: Map<number, ChitchatGroup>
) => {
  // 测试
  const sendMessage = function(data: any) {
    const user = userChitchat.get(data.token);
    if (user?.token == data.token) {
      console.log(user?.username + "说：" + data.message);
      io.to("public").emit("receiveMessage", { ...user, message: data.message, token: null });
      return;
    }
  };
  // 好友发消息
  const sendMessageById = function(data: any) {
    const user = userChitchat.get(data.token);
    if (user?.token == data.token) {
      let targetId = data.friend_id;
      if (!targetId) {
        return;
      }
      let roomName =
        (user?.user_id || 0) > targetId
          ? user?.user_id + "" + targetId
          : targetId + "" + user?.user_id;
      console.log(roomName + "---" + user?.username + "说：" + data.message);
      const admin = new ChitchatUser(user as ChitchatUser);
      io.to(roomName).emit("receiveMessageById", {
        ...admin,
        message: data.message,
        token: null,
        friend_id: data.friend_id,
      });
      return;
    }
  };
  const sendMessageGroup = function(data: any) {
    const user = userChitchat.get(data.token);
    if (user?.token == data.token && data?.group_id!=null) {
      let group = groupChitchat.get(data?.group_id);
      let flag = group?.member?.get(user?.user_id || -1);
      // 群里没有成员则结束
      if (flag) {
        return;
      }
      console.log(data?.group_id);
      
      let roomName = (group?.group_id) + (group?.groupname || "");
      console.log(roomName + "---" + user?.username + "说：" + data.message);
      const admin = new ChitchatUser(user as ChitchatUser);
      io.to(roomName).emit("receiveMessageGroup", {
        ...admin,
        message: data.message,
        token: null,
        group_id: data.group_id,
      });
      return;
    }
  };
  return {
    sendMessage,
    sendMessageById,
    sendMessageGroup,
  };
};
